<template>
	<div class="container container-all">
		<div class="margin-neg main-box">
			<h4 class="title">查询</h4>
			<div class="query-box">
				<div class="query-type">
					<Radio-group v-model="queryType" @on-change="handelType">
						<Radio v-for="(item, index) in queryOptions" :key="index" :label="item.value">
							<span>{{ item.label }}</span>
						</Radio>
					</Radio-group>
				</div>
				<div class="query-inp">
					<div class="input-bar">
						<Input v-model="query" :placeholder="prompt" @keyup.enter.native="getQuery(queryType)"></Input>
					</div>
					<div class="button-bar">
						<Button type="primary" icon="ios-search" @click="getQuery(queryType)">查询</Button>
					</div>
				</div>
			</div>
			<!-- 结果展示 -->
			<div class="content-box">
				<div class="no-data" v-if="result.length === 0 && !loading">
					暂无数据
				</div>
				<!-- 表格数据 -->
				<div v-if="result.length > 0" class="table-box">
					<device-data :devList="result" @pauseTime="pauseTime"></device-data>
				</div>
				<Spin class="loading" fix size="large" v-if="loading"></Spin>
			</div>
		</div>
	</div>
</template>

<script>
import { queryOptions } from '../assets/js/select-data'
import deviceData from './common/device-data'
import detail from './detail'
export default {
	components: {
		deviceData,
		detail
	},
	data() {
		return {
			query: '', // 查询的条件
			prompt: (this.queryType === 'order') ? '请输入订单号...' : '请输入设备ID...', // 提示内容
			queryOptions: queryOptions, // 查询选项内容
			queryType: 'device', // 查询类别（设备，运单）
			result: [], // 查询结果
			findId: [], // 已存在的设备id
			interval: null
		}
	},
	computed: {
		deviceData() {
			return this.$store.getters.get_result
		},
		loading() {
			return this.$store.getters.get_loading
		}
	},
	methods: {
		// 查询条件（类型选项，设备id,订单）
		handelType(val) {
			this.queryType = val
			this.prompt = (val === 'order') ? '请输入订单号...' : '请输入设备ID...'
		},
		// 查询data
		setQueryData() {
			let data = {
				ordersAirWayBillNo: '',
				startTime: '2000-01-01 01:30:10',
				endTime: this.$moment().format('YYYY-MM-DD HH:mm:ss')
			}
			return data
		},
		// 查询
		async new_get(data) {
			const res = await this.$http.post('/query', data)
			if (res.data.data.length > 0) {
				// 判断查询的是订单号还是设备ID
				if (data.query_type === '4') {
					this.result = this.result.concat(res.data.data)
				} else {
					// 如果是订单号，比较列表中是否存在数据
					let arr = []
					// 存在的数据
					let idOld = new Set(this.result.map(id => id.serialId))
					// 新返回的数据
					let idRes = new Set(res.data.data.map(id => id.serialId))
					// 交集
					let idAll = new Set([...idOld].filter(id => idRes.has(id)))
					// 判断是否存在交集
					res.data.data.forEach(item => {
						if (!idAll.has(item.serialId)) {
							arr.push(item)
						}
					})
					// 将不重复的id号和原数组拼接
					this.result = this.result.concat(arr)
				}
				this.$store.commit('set_storage', this.result)
			} else {
				throw '未查询到数据'
			}
		},
		// 格式化localStorage保存的id
		get_storage() {
			let idArray = localStorage.getItem('idArray')
			let arr = []
			if (idArray) {
				arr = idArray.split(',')
			}
			return arr
		},
		// 查询
		getQuery(val) {
			let data = this.setQueryData()
			if (val === 'device') {
				data.serialId = this.query
				data.query_type = '4'
			} else {
				data.ordersAirWayBillNo = this.query
				data.serialId = ''
				data.query_type = '1'
			}

			if (this.get_storage().includes(data.serialId)) {
				this.$Message.error('列表中已存在查询数据，请在列表中点击刷新！')
				return false
			}
			this.$store.commit('set_load', true)
			this.new_get(data).then(() => {
				this.$store.commit('set_load', false)
			}).catch(error => {
				this.$Message.error(error)
				this.$store.commit('set_load', false)
			})
		},
		// 加载时候判断localStorage中的数据查询
		async load_get(id) {
			let data = this.setQueryData()
			data.query_type = '4'
			data.serialId = id
			this.$store.commit('set_load', true)
			const res = await this.$http.post('/query', data)
			if (res.data.data.length > 0) {
				this.result = this.result.concat(res.data.data)
			} else {
				throw '未查询到数据'
			}
			this.$store.commit('set_load', false)
		},
		load_query() {
			let idArray = this.get_storage()
			idArray.forEach(item => {
				this.load_get(item).then(() => {
					console.log(item + '数据已查询')
				}).catch(error => {
					this.$Message.error(item + error)
				})
			})
		},
		// 定时刷新
		toRefresh() {
			// 定时查询, 不关网页默认一天刷新一次
			let time = localStorage.getItem('retime') ? parseInt(localStorage.getItem('retime')) : 86400000
			this.interval = setInterval(() => {
				this.result = []
				this.load_query()
			}, time)
		},
		// 暂停定时
		pauseTime(state) {
			// stop: 停止, start: 开启
			if (state === 'stop') {
				clearInterval(this.interval)
				this.interval = null
			} else {
				this.toRefresh()
			}
		}
	},
	mounted() {
		this.load_query() // 首次执行
		this.toRefresh() // 开启定时查询
	}
}
</script>

<style lang="less" scoped>
@import '../assets/css/home';

.title {
	padding-left: 15px;
	line-height: 28px;
	height: 28px;
	border-bottom: 1px solid #ddd;
}

.main-box {
	height: 100%;
	.clear-fix;
}

.query-box {
	padding: 15px;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	.border-local(bottom, #ddd);

	>div {
		.margin(left, 20px);
	}

	.query-inp {
		>div {
			float: left;
		}

		.input-bar {
			width: 300px;
		}

		/deep/ .ivu-input {
			border-radius: 4px 0 0 4px;
		}

		/deep/ .ivu-btn {
			border-radius: 0 4px 4px 0;
		}
	}
}

.content-box {
	height: calc(~"100% - 61px");
	padding: 15px;
	flex: 1;
	position: relative;

	.no-data {
		text-align: center;
		width: 100%;
		font-size: 18px;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translateX(-50%) translateY(-50%);
	}

	.table-box {
		margin: -15px;
	}
}
</style>
